<template>
  <el-container :class="{'analysis-chart-container':stayChart}">
    <el-main>
      <el-tabs v-model="activeTab" v-loading="chartLoading" @tab-click="tabClick">
        <el-tab-pane label="同比趋势" name="tb">
          <el-row type="flex" justify="space-between" align="middle">
            <div>
              <el-switch v-model="isDateType" active-text="按日" inactive-text="按月" style="margin-right: 20px"></el-switch>
              <el-date-picker
                v-if="isDateType"
                v-model="query.time"
                type="date"
                align="right"
                :clearable="false"
                value-format="yyyy-MM-dd"></el-date-picker>
              <el-date-picker
                v-if="!isDateType"
                v-model="query.month"
                type="month"
                align="right"
                :clearable="false"
                value-format="yyyy-MM"></el-date-picker>
              <el-button style="margin-left: 10px" type="primary" @click="fetchTbData">筛选</el-button>
            </div>
            <el-button size="mini" :icon="stayChart?'el-icon-lock':'el-icon-unlock'" circle @click.native="fixedChartContainer" />
          </el-row>
          <div style="margin-bottom: 30px"></div>
          <el-empty description="暂无同比趋势数据" v-if="!tbData"/>
          <el-row :gutter="20" v-if="tbData">
            <el-col class="chart-cell" :span="24" v-for="(item,index) in tbData" :key="index" v-if="tbReload">
              <line-bar-chart ref="tbChart" :height="'350px'" :chart-data="item" :line-color="lineColor" :bar-color="barColor" />
            </el-col>
          </el-row>

        </el-tab-pane>
        <el-tab-pane label="环比趋势" name="hb">
          <el-row type="flex" justify="space-between" align="middle">
            <div>
              <el-switch v-model="isDateRange" active-text="按日" inactive-text="按月" style="margin-right: 20px"></el-switch>
              <el-date-picker
                v-if="isDateRange"
                v-model="query.dateRange"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable="false"
                :picker-options="datePickerOpts"></el-date-picker>
              <el-date-picker
                v-if="!isDateRange"
                v-model="query.monthRange"
                type="monthrange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                :clearable="false"
                :picker-options="monthPickerOpts"
                value-format="yyyy-MM"></el-date-picker>
              <el-button style="margin-left: 10px" type="primary" @click="fetchHbData">筛选</el-button>
            </div>
            <el-button size="mini" :icon="stayChart?'el-icon-lock':'el-icon-unlock'" circle @click.native="fixedChartContainer" />
          </el-row>
          <div style="margin-bottom: 30px"></div>
          <el-empty description="暂无环比趋势数据" v-if="!hbData"/>
          <el-row :gutter="20" v-if="hbData">
            <el-col class="chart-cell" :span="24" v-for="(item,index) in hbData" :key="index" v-if="hbReload">
              <line-bar-chart ref="hbChart" :height="'350px'" :chart-data="item" :line-color="lineColor" :bar-color="barColor" />
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-main>
  </el-container>
</template>

<script>
  import {parseTime} from "@/utils";
  import analyApi from '@/api/analysis'
  import LineChart from "./LineChart";
  import LineBarChart from "./LineBarChart";
  const today = parseTime(new Date(), '{y}-{m}-{d}')
  const yestoday = parseTime(new Date().getTime()-1000*24*3600,'{y}-{m}-{d}')
  const sevenDayAgo = parseTime(new Date().getTime()-1000*24*3600*7,'{y}-{m}-{d}')
  const threeMonthAgo = parseTime(new Date().getTime()-1000*24*3600*90,'{y}-{m}-{d}')
  export default {
    name: "bigdata-analysis",
    components:{
      LineChart,
      LineBarChart
    },
    data(){
      return {
        activeTab:'tb',
        isDateType:true,
        isDateRange:true,
        tableData:null,
        chartLoading:false,
        tbReload:true,
        hbReload:false,
        stayChart:false,
        query:{
          orgnization_ids:[],
          time:yestoday,
          month:yestoday,
          dateRange:[sevenDayAgo,today],
          monthRange:[threeMonthAgo, today],
        },
        lineColor:'#d5d730',
        barColor:'#1890ff',
        tbData:null,
        hbData:null,
        datePickerOpts: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        monthPickerOpts: {
          shortcuts: [{
            text: '本月',
            onClick(picker) {
              picker.$emit('pick', [new Date(), new Date()]);
            }
          }, {
            text: '今年至今',
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近六个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      }
    },
    created() {
      const choiceOrgs=this.$parent.$parent.$data.orgQuery.orgnization_ids
      this.query.orgnization_ids=choiceOrgs
      this.chartsData()
    },
    methods:{
      fetchData(){
        this.$nextTick(() => {
          this.chartsData()
        })
      },
      factorysSelected(query){
        this.query.orgnization_ids = query.orgnization_ids
        this.fetchData()
      },
      chartsData(){
        if (!this.query.orgnization_ids.length){
          this.$message.warning("请选择组织!")
          this.tbData=null
          this.hbData=null
          return
        }
        this.fetchTbData()
        this.fetchHbData()
      },
      fetchTbData(){
        let tbParams = {}
        tbParams.orgnization_id = this.query.orgnization_ids.join(',')
        tbParams.time = this.isDateType?this.query.time:this.query.month
        if (!this.isDateType){
          const dArr = this.query.month.split('-')
          if (dArr.length>2)
            tbParams.time = `${dArr[0]}-${dArr[1]}`
        }
        this.chartLoading=true
        analyApi.analysisTbRatio(tbParams).then(res=>{
          const dataArr =res.data
          this.tbData = this.convertChartData(dataArr)
          this.chartLoading=false
        })
      },
      fetchHbData(){
        let hbParams = {}
        hbParams.orgnization_id = this.query.orgnization_ids.join(',')
        hbParams.start =this.isDateRange?this.query.dateRange[0]:this.query.monthRange[0]
        hbParams.end =this.isDateRange? this.query.dateRange[1]:this.query.monthRange[1]
        if (!hbParams.start||!hbParams.end){
          this.$message.error("日期选择不能为空")
          return
        }
        if (!this.isDateRange){
          const startDArr = this.query.monthRange[0].split('-')
          const endDArr = this.query.monthRange[1].split('-')
          if (startDArr.length>2)
            hbParams.start = `${startDArr[0]}-${startDArr[1]}`
          if (endDArr.length>2)
            hbParams.end = `${endDArr[0]}-${endDArr[1]}`
        }
        this.chartLoading=true
        analyApi.analysisHbRatio(hbParams).then(res=>{
          const dataArr = res.data
          this.hbData = this.convertChartData(dataArr,'环比')
          this.chartLoading=false
        })
      },
      convertChartData(dataArr,type='同比'){
        let chartsOpts = []
        for (let cdata of dataArr){
          let chartOpt = {
            names:[cdata.name,type],
            messures:[cdata.messure,'%'],
            xValues:Object.keys(cdata.data),
            yValues:[Object.values(cdata.data), Object.values(cdata.ratio)]
          }
          chartsOpts.push(chartOpt)
        }
        return chartsOpts
      },
      tabClick(tab){
        this.hbReload = tab.index !== '0'
        this.tbReload=!this.hbReload
      },
      fixedChartContainer(){
        this.stayChart = !this.stayChart
        if (this.stayChart)
          this.$message.success("您固定了图表")
        else
          this.$message.success("您取消了图表固定")
      }
    }
  }
</script>

<style scoped lang="scss">
  .analysis-chart-container{
    position: fixed;
    padding: 5px;
    top: 80px;
    right: 0;
    width: calc(100% - 561px);
  }
  .chart-cell{
    padding: 10px;
    height: 350px;
    margin-top: 10px;
    margin-bottom: 30px;
    display: flex;
    align-items: flex-end;
  }

</style>
